# -*- coding: UTF-8 -*-
"""
Course:        CS408 Computer Science Project B, TEAM 1
Semester:      2010 SPRING
Project:       DOHN(Web-based Account Book System)

File:          mobiles.py
Description:   Shortcut input for mobile web page
Class:         MobileView, MobileController

Author:        Gangmin Park
"""

import sessions
import db
import views
import shortcuts
import utils
import mod_python
import string
import transactions

"""
@note: This methods are replaced into dohn.py
def index(req, option = 0):
    
    if 1 == option:    # login error
        return utils.get_html_with_msg( "m_main.html",
                                        "Login Error! Check ID or Password.")
    
    if sessions.check_signed(req):
        mobile_obj = MobileView()
        return mobile_obj.show_list_window(req)
    else:
        mobile_obj = MobileView()
        return mobile_obj.show_signin_window(req)

def show_add_window(req, description):
    mobile_obj = MobileView()
    return mobile_obj.show_add_window(req, description)

def on_click_confirm(req, button):
    
    if button=="cancel":
        mobile_obj = MobileController()
        return mobile_obj.on_click_cancel(req)
    else:
        mobile_obj = MobileController()
        return mobile_obj.on_click_confirm(req, button)
"""



class MobileView:
    """
    Mobile View
    """
    def show_index_window(self, req, option = 0):
        """
        @author: Gangmin Park
        @summary: Show index window.
        @param req: request, option
        @return: Shortcut list page(signed in), Mobile sign in page(not signed in)
        """
        
        if 1 == option:    # login error
            return utils.get_html_with_msg( "m_main.html",
                                            "Login Error! Check ID or Password.")
        
        if sessions.check_signed(req):
            mobile_obj = MobileView()
            return mobile_obj.show_list_window(req)
        else:
            mobile_obj = MobileView()
            return mobile_obj.show_signin_window(req)
            
    def show_signin_window(self, req):
        """
        @author: Gangmin Park
        @summary: Show the mobile sign-in widow
        @param req: request
        @return: HTML source of Mobile sign-in window
        @note: We need a seperate view method of sign in.
        """
        
        src_path = utils.get_abs_path() + "/html/m_main.html"
        src = utils.get_file_content(src_path)
        return src
    
    def show_list_window(self, req):
        """
        @author: Gangmin Park
        @summary: Show the mobile shortcut lists
        @param req: request
        @return: HTML source of shortcut lists window 
        """
        
        session_id = sessions.get_id(req)
        query = "SELECT description, amount FROM shortcut_tb WHERE user_id = '%s'" % (session_id)
        data = db.run_query(query)
        
        src_path = src_path = utils.get_abs_path() + "/html/m_shorcut.html"
        
        in_src = []
        count = 0
        for atuple in data:
            
            if count == 3 :
                in_src.append("<tr>\n")
                count = 0
            
            # Reference: http://forums.digitalpoint.com/showthread.php?t=246201
            in_src.append("<td height=\"70\">" + \
                          "<button name =\"description\" value = '%s' class=btn>" % str(atuple[0]).strip())
                
            for j in range(2):
                if 0 == j:    # if 1st, date
                    aitem = str(atuple[j]).strip()
                    in_src.append("%s<br><br>" % (aitem))
                elif 1 == j:  # if 3rd, amount
                    aitem = str(atuple[j]).strip()
                    aitem = "%d" % (float(aitem))    
                    in_src.append("%s" % (aitem))
            
            in_src.append("</button></td>")
            count = count + 1
            
            if count == 3:
                in_src.append("</tr>\n")
            
        in_src = ''.join(in_src)
          
        src = utils.replace("m_shorcut.html", in_src)
        
        return src
    
    def show_add_window(self, req, description):
        """
        @author: Gangmin Park
        @summary: Show the add shortcut window
        @param req: request
        @paran description: the shortcut's transaction description
        @return: HTML source of shortcut transaction add window
        """
           
        src_path = utils.get_abs_path() + "/html/m_shortcut_2.html"
        
        session_id = sessions.get_id(req)
        query = "SELECT description, amount, " + \
                "plan_remain, plan_total, category, num " + \
                "FROM shortcut_tb " + \
                "WHERE (user_id = '%s' AND description = '%s')" % (session_id, description)
        data = db.run_query(query)

        #mobile_obj = aShortcut()
        #aShortcut.__init__()
        
        in_src = []
        amount = 0
        plan_remain = 0
        category = 0
        num = 0
        for atuple in data:
            for j in range(6):
                if 0 == j:    # if description
                    in_src.append("<h1>")
                    aitem = str(atuple[j]).strip()
                    in_src.append("%s" % (aitem))
                    in_src.append("</h1>")
                elif 1 == j:    #if amount
                    in_src.append("<p><strong>")
                    aitem = str(atuple[j]).strip()
                    aitem = str("%d" % (float(aitem)))
                    in_src.append("%s" % (aitem))
                    in_src.append("</strong> won</p>")
                    amount = int(aitem)
                elif 2 == j:
                    in_src.append("<p>");
                    aitem = str(atuple[j]).strip()
                    aitem = str("%d" % (int(aitem)))
                    in_src.append("Count: <strong>%s/" % (aitem))
                    plan_remain = int(aitem)
                elif 3 == j:
                    aitem = str(atuple[j]).strip()
                    aitem = str("%d" % (int(aitem)))
                    in_src.append("%s" % (aitem))
                    in_src.append("</strong></p>")
                elif 4 == j:    #if category
                    in_src.append("")
                    cat_str = str(atuple[j]).strip()
                    category = int(cat_str)
                    aitem = str(utils.get_category_name(atuple[j])).strip()
                    in_src.append("Category: %s" % (aitem))
                    in_src.append("<br><br>")
                elif 5 == j:
                    aitem = str(atuple[j]).strip()
                    num = int(aitem)
                    
        in_src.append("<button name=\"button\" value='%s|%d|%d|%d|%d' class=btnconfirm></button> \
        <button name=\"button\" value=cancel class=btncancel></button>" % (description, amount, category, plan_remain, num))
        in_src = ''.join(in_src)
        
        src = utils.replace("m_shortcut_2.html", in_src)
        
        return src
        
class MobileController:
    """
    Mobile Controller
    """
    def on_click_confirm(self, req, button):
        """
        @author: Gangmin Park
        @summary: If the user click the 'Confirm' button on shortcut transaction add window
                  then add it to transaction data base.
        @param req: request
        @param button: value of button is the shortcut's transaction description
        """
        value = str(button).split("|")
        description = str(value[0])
        amount = int(value[1])
        category = int(value[2])
        plan_remain = int(value[3])
        num = int(value[4])
        
        session_id = sessions.get_id(req)
        
        """
        query = "SELECT description, amount, category FROM shortcut_tb WHERE (user_id = '%s' AND description = '%s')" % (session_id, button)
        data = db.run_query(query)
        
        for atuple in data:
            for j in range(3):
                if 0 == j:    # if description
                    description = str(atuple[j]).strip()
                elif 1 == j:    #if amount
                    aitem = str(atuple[j]).strip()
                    amount = float(aitem)
                elif 2 == j:    #if category
                    aitem = str(atuple[j]).strip()
                    category = int(aitem)
                    #category = str(utils.get_category_name(atuple[j])).strip()
        """
        #mobile_obj = TransactionController();
        #mobile_obj.query_add_transaction(utils.get_current_date(), description, amount, category)
        
        query = "INSERT INTO transaction_tb (user_id, date, description, " + \
                "amount, category, deleted) VALUES " + \
                "('%s', '%s 00:00:00', '%s', '%f', '%d', '0')" \
                % (session_id, utils.get_current_date(), description, amount, category)
        
        db.execute_query(query)
        
        if plan_remain == 0:
            src_path = utils.get_abs_path() + "/html/m_warning.html"
            src = utils.get_file_content(src_path)
            return src
        else :
            plan_remain -= 1
            query = "UPDATE shortcut_tb SET plan_remain='%d' WHERE num='%d'" % (plan_remain, num)
            db.execute_query(query)
            
        #notice = """<script>alert("Transaction recorded"); location.replace("mobile_list");</script>")"""
        utils.redirect(req, "mobile_list")
        
 #           in_src = ''.join(in_src)            
        return notice
#        utils.redirect(req, 'mobile_list')
        
    def on_click_cancel(self, req):
        """
        @author: Gangmin Park
        @summary: If the user click the 'Cancle' button on shortcut transaction add window
                  then redirect the page to shortcut list.
        @param req: request
        """
        
        utils.redirect(req, "mobile_list")
        